package cn.weekimwee.firstlineofcodeforkotlin.unit6

import android.content.SharedPreferences
import android.os.Bundle
import android.preference.PreferenceManager
import android.view.View
import cn.weekimwee.firstlineofcodeforkotlin.BaseActivity
import cn.weekimwee.firstlineofcodeforkotlin.R
import kotlinx.android.synthetic.main.activity_save_file.*

class SharedPreferencesActivity : BaseActivity() {
    private lateinit var pref: SharedPreferences
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_save_file)
        save.setOnClickListener { it.onClick() }
        show.setOnClickListener { it.onClick() }
        pref = PreferenceManager.getDefaultSharedPreferences(this)
        text.text = pref.getString("string", "nothing")
    }

    private fun View.onClick() {
        when (this.id) {
            R.id.save -> {
                val editor = pref.edit()
                editor.putString("string", edit.text.toString())
                editor.apply()
            }
            R.id.show -> {
                text.text = pref.getString("string", "nothing")
            }
        }
    }
}
